angular.module('LocalUser', []).service('$User', [ function () {
    var storage = window.localStorage;
    var UESR_HASH = '__USER_HASH__';
    var _userObj = {id:2,name:'TESTER'};
    var _service = {
        //从localstorage中加载用户数据
        //登录成功之后，调用该方法
        reload:function(u){
            if(u){
                storage.setItem(UESR_HASH,JSON.stringify(u));
            }
            var _val = storage.getItem(UESR_HASH);
            if(_val == 'false' || !_val){
                return false;
            }
            _userObj = JSON.parse(_val);
            return true;
        },
        get:function(k){
            if(k)
                return _userObj[k];
            return _userObj;
        },
        set:function(k,v){
            _userObj[k] = v;
        },
        reLogin:function(){
            //TODO:验证用户是否需要重新登录，用户信息是否失效

        },
        clear:function(){
            storage.setItem(UESR_HASH,'false');
        }
    };

    return _service;
}]);

service.factory('appFactory',['$q','$timeout','$ae','$cordovaDevice','$cordovaAppVersion','$User',
    function($q,$timeout,$ae,$cordovaDevice,$cordovaAppVersion,$User){
    var _data = {isLogin:false};
    var _service = {
        ready:function(){
            var q = $q.defer();
            q.resolve({});
            return q.promise;
        },
        /**
         *登陆
         * @param username
         * @param password
         * @returns {*} promise
         */
        doLogin:function(username,password) {
           var q =$q.defer();
            var platform = $cordovaDevice.getPlatform();
            var checkCallback = function(build){
                var o = new $ae.Function('api.logistics.login');
                o.invoke({
                    'phone':username,
                    'password':password,
                    'device':platform.toLowerCase(),
                    'version':build
                }).then(function(data){
                    _data.isLogin = true;
                    $User.reload(data);
                    q.resolve({code:0,data:data});
                }).catch(function(err){
                    alert(JSON.stringify(err));
                    q.reject({code:-1,data:err});
                });
            };
            if('iOS' == platform){
                $cordovaAppVersion.getVersionCode().then(checkCallback);
            }else{
                $cordovaAppVersion.getVersionNumber().then(checkCallback);
            }
            return q.promise;
        },
        /**
         * 是否登录
         * @returns {boolean}
         */
        isLogin:function(){
            _data.isLogin = $User.reload();
            return _data.isLogin;
        },
        /**
         * 登出
         */
        loginOut:function(){
            $User.clear();
            _data.isLogin=false;
        },
        /***
         * 获取订单信息
         * @author Scor
         */
        findOrder:function(param){
            var q = $q.defer();
            var func = new $ae.Function('api.logistics.findOrder');
            func.invoke(param).then(function(data){
                q.resolve(data);
            }).catch(function (err) {
                q.reject(err);
            });
            return q.promise;
        },
        /***
         * 获取甩单信息
         * @author Scor
         */
        getTransferOrder:function(param){
            var q = $q.defer();
            var func = new $ae.Function('api.logistics.getTransferOrder');
            func.invoke(param).then(function(data){
                q.resolve(data);
            }).catch(function (err) {
                q.reject(err);
            });
            return q.promise;
        },
        /***
         *领取订单
         * @author scor
         * @param order
         * @returns {*}
         */
        acceptOrder:function(param){
            var q = $q.defer();
            var f = new $ae.Function('api.logistics.newMission');
            f.invoke(param).then(function(data){
                q.resolve(data);
            }).catch(function(err){
                q.reject(err);
            });
           return q.promise;
        },
        /***
         * 查询订单并改变状态为7000
         * @author Scor
         * @param orderid
         * @returns {*}
         */
        orderAccepted:function(orderid){
            var q = $q.defer();
            var func = new $ae.Function('ec.update');
            func.invoke({table:"gr_order",condition:"orderid = '"+orderid+"' AND status < 7000",row:{status:7000}}).then(function(d){
                q.resolve(d);
            }).catch(function (e) {
                q.reject(e);
            });
            return q.promise;
        },
        /***
         * 快递员扫码领取快件
         * @author zhangwei
         */
        getExpress1:function(param){
            var q = $q.defer();
            var func = new $ae.Function('api.logistics.getExpress1');
            func.invoke(param).then(function(data){
                q.resolve(data);
            }).catch(function (err) {
                q.reject(err);
            });
            return q.promise;
        },
        /***
         * 站长扫码领取快件
         * @author zhangwei
         */
        getExpress2:function(param){
            var q = $q.defer();
            var func = new $ae.Function('api.logistics.getExpress2');
            func.invoke(param).then(function(data){
                q.resolve(data);
            }).catch(function (err) {
                q.reject(err);
            });
            return q.promise;
        },
        /***
         * 扫码查单
         * @author zhangwei
         */
        getOrderStatus:function(param){
            var q = $q.defer();
            var func = new $ae.Function('api.logistics.getOrderStatus');
            func.invoke(param).then(function(data){
                q.resolve(data);
            }).catch(function (err) {
                q.reject(err);
            });
            return q.promise;
        }
    };
    return _service;
}]);

service.factory('CheckVersion',['$q','$ae','$cordovaDevice','$cordovaAppVersion',function($q,$ae,$cordovaDevice,$cordovaAppVersion){

    return {
        checkUpdate:function(){
            var q = $q.defer();
            var platform = $cordovaDevice.getPlatform();
            var checkCallback = function(build){
                var func = new $ae.Function('api.version.check');
                var args = {app:'EXPAPP',device:platform.toLowerCase(),version:build};
                func.invoke(args).then(function(d){
                    q.resolve(d);
                }).catch(function (e) {
                    //包含version和download
                    e.download= e.error.download;
                    q.reject(e);
                });
            };
            if('iOS' == platform){
                $cordovaAppVersion.getVersionCode().then(checkCallback);
            }else{
                $cordovaAppVersion.getVersionNumber().then(checkCallback);
            }

            return q.promise;

        }
    }
}]);
service.factory('Push', function() {
    var push;
    return {
        setBadge: function(badge) {
            if (push) {
                plugins.jPushPlugin.setBadge(badge);
            }
        },
        setAlias: function(alias) {
            if (push) {
                plugins.jPushPlugin.setAlias(alias);
            }
        },
        setTags:function(tags){
            if(push){
                plugins.jPushPlugin.setTags(tags);
            }
        },
        check: function() {
            if (window.jpush && push) {
                plugins.jPushPlugin.receiveNotificationIniOSCallback(window.jpush);
                window.jpush = null;
            }
        },
        init: function(notificationCallback) {
            push = window.plugins && window.plugins.jPushPlugin;
            if (push) {
                plugins.jPushPlugin.init();
                plugins.jPushPlugin.setDebugMode(true);
                plugins.jPushPlugin.openNotificationInAndroidCallback = notificationCallback;
                plugins.jPushPlugin.openNotificationIniOSCallback = notificationCallback;
            }
        }
    };
});

service.factory('NotificationFactory',['$q','$ae',function($q,$ae){
    var _service = {
        list:function(uid){
            var q = $q.defer();
            var query = new $ae.Query('nf_record');
            //当前用户的消息
            query.condition("alias = '"+ uid+"'");
            //全局的通知消息
            query.or("alias = 'ALL'");
            query.sort('createAt-');
            query.find().then(function(list){
                //TODO:处理一下通知的列表数据
                q.resolve(list);
            }).catch(function(err){
                q.reject(err);
            });

            return q.promise;
        },
        //读取消息记录
        read:function(notification_id){
            var q = $q.defer();
            var noti = new $ae.Object('nf_record');
            noti.getById(notification_id).then(function(data){
                //设置已读
                data.set('isread',1);
                data.save().then(function(res){
                    q.resolve(res);
                }).catch(function(err){
                    q.reject(err);
                })
            }).catch(function(err){
                q.reject(err);
            });
            return q.promise;
        },
        count:function(uid){
            var q = $q.defer();
            var query = new $ae.Query('nf_record');
            query.and("isread = 0");
            //当前用户的消息
            //全局的通知消息
            query.and("(alias = '"+ uid+"' or alias = 'ALL')");
            query.count().then(function(c){
                q.resolve(c);
            }).catch(function(err){
                q.reject(err);
            });

            return q.promise;
        }
    };
    return _service;
}]);

service.factory('GpsFactory',['$q','$ae',function($q,$ae){
    var _service = {
        sync:function(client,geo){
            var q = $q.defer();
            var o = new $ae.Object('lg_location_record');
            //当前用户的消息
            o.set('clientId',''+client);
            o.set('latitude',''+geo.latitude);
            o.set('longitude',''+geo.longitude);
            //全局的通知消息
            o.create().then(function(data){
                q.resolve(data);
            }).catch(function(err){
                q.reject(err);
            });

            return q.promise;
        }
    };
    return _service;
}]);
